package com.leyou.sms.mq;

import com.leyou.sms.config.SmsProperties;
import com.leyou.sms.utils.SmsUtil;
import com.leyou.test.enums.ExceptionEnum;
import com.leyou.test.exceptions.LyException;
import com.leyou.utils.JsonUtils;
import com.sun.jmx.snmp.internal.SnmpMsgProcessingSubSystem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.constants.MQConstants.RoutingKey.*;
import static com.leyou.constants.MQConstants.Queue.*;
import static com.leyou.constants.MQConstants.Exchange.*;

@Component
@Slf4j
@EnableConfigurationProperties(SmsProperties.class)
public class SmsListener {
    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private SmsUtil smsUtil;

    /**
     * 注册时发送短信验证码的方法
     * 使用RabbitMQ的监听机制(接收到消息,执行此方法)
     * @param msg
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = VERIFY_CODE_KEY
    ))
    public void listenVerifyCode(Map<String, String> msg) {
        //校验参数是否为空
        if (CollectionUtils.isEmpty(msg)) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        //取出手机号码phone,并且删除这个键值对
        String phone = msg.remove("phone");
        //校验phone是否未空
        if (StringUtils.isBlank(phone)) {
            throw new LyException(ExceptionEnum.INVALID_PHONE_NUMBER);
        }
        //此时map中只剩下短信模板中的变量{"code":"..."},因此可以直接将其转换为json格式
        String code = JsonUtils.toString(msg);
        //校验短信验证码中的变量是否未空
        if (StringUtils.isBlank(code)) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        try {
            //调取smsUtil工具类的发送短信的方法
            smsUtil.sendMessage(
                    phone,
                    smsProperties.getSignName(),
                    smsProperties.getVerifyCodeTemplate(),
                    code);
        } catch (Exception e) {
            //如果发送短信失败,直接try,不进行RabbitMQ的重试
            log.error("【SMS服务】短信验证码发送失败", e);
        }
    }
}
